package com.zsc.newbuds.controller.admin;
import java.io.*;
import java.io.OutputStream;
import java.net.URLEncoder;
import	java.util.ArrayList;

import com.alibaba.excel.EasyExcel;
import com.zsc.newbuds.consts.Consts;
import com.zsc.newbuds.entity.*;
import com.zsc.newbuds.service.impl.*;
import com.zsc.newbuds.utils.OssUtil;
import com.zsc.newbuds.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 捐赠管理的控制器
 * @author D
 */
@RequestMapping("admin/donationManagement")
@Controller
public class DonationController {

    @Resource
    OssUtil ossUtil;

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    RecordServiceImpl recordService;
    @Autowired
    RecycleServiceImpl recycleService;

    @Autowired
    SaleRecordServiceImpl saleRecordService;

    @Autowired
    AdminServiceImpl adminService;

    @Autowired
    UserServiceImpl userService;

    @Autowired
    DonationAreaServiceImpl donationAreaService;

    @ResponseBody
    @GetMapping("/getDonationList")
    public List<Recycle> getDonationList(){
        return recycleService.getRecycleList();
    }

    @ResponseBody
    @GetMapping("/sortingDonation")
    public String sortingDonation(Integer recycleId, int clothesNumber, int booksNumber, HttpServletResponse response) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try{

            List<ImageData> imageDataList = new ArrayList<>();
            imageDataList = recordService.addRecord(recycleId,clothesNumber,booksNumber);
            recycleService.updateState(recycleId,"已分拣");

            EasyExcel.write(out, ImageData.class).sheet("回收记录二维码").doWrite(imageDataList);
            InputStream inputStream = parse(out);
            //将二维码表格存入oss
            String excelUrl = ossUtil.upLoadExcel(inputStream);
            String key = "excelUrl:"+recycleId.toString();
            //OSS地址存入redis
            redisUtil.set(key,excelUrl);
            return excelUrl;
        }catch (Exception e){
            e.printStackTrace();
            return "";
        }
    }

    @ResponseBody
    @GetMapping("/download")
    public String download(Integer id) {
        String key = "excelUrl:"+id.toString();
        return (String) redisUtil.get(key);
    }

    @ResponseBody
    @PostMapping("/getAdminInfo")
    public Admin getAdminInfo(Integer adminId){
        return adminService.getAdminInfo(adminId);
    }

    @ResponseBody
    @PostMapping("/getUserInfo")
    public User getUserInfo(Integer userId){
        return userService.getUserInfo(userId);
    }

    @ResponseBody
    @GetMapping("/getDonationRecordList")
    public List<Record> getDonationRecordList(){
        return recordService.getRecordList();
    }

    @ResponseBody
    @PostMapping("/distributionArea")
    public int distributionArea(Integer[] recordId){
        recordService.setDistributionRecord(recordId);
        return 1;
    }

    @ResponseBody
    @GetMapping("/getDonationAreaList")
    public List<DonationArea> getDonationAreaList(){
        return donationAreaService.getDonationAreaList();
    }

    @ResponseBody
    @GetMapping("/getDistributionRecord")
    public List<Record> getDistributionRecord(){
        return recordService.getDistributionRecord();
    }

    /**
     * 将选中的记录分发到捐赠地址
     * @param areaId
     * @param area
     * @param recordId
     * @return
     */
    @ResponseBody
    @PostMapping("/allocateDonationArea")
    public int allocateDonationArea(Integer areaId,String area,Integer[] recordId){
        System.out.println(areaId+area+ Arrays.toString(recordId));
        try {
            recordService.allocateDonationArea(area,recordId);
            donationAreaService.updateTimes(areaId);
            return 1;
        }catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 将衣物回收并生生成回收表
     * @return
     */
    @ResponseBody
    @PostMapping("/discardedClothing")
    public int discardedClothing(Integer[] recordId){
        try{
            saleRecordService.setSaleRecord(recordId);
            return 1;
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }



    @ResponseBody
    @GetMapping("/getSaleList")
    public List<Record> getSaleList(){
        return recordService.getSaleList();
    }

    /**
     * 获取出售的重重量
     * @param recycleId
     * @return
     */
    @ResponseBody
    @PostMapping("/getWeight")
    public Map<String, Object> getWeight(Integer[] recycleId){
        Map<String, Object> map = new HashMap<>();
        System.out.println(Arrays.toString(recycleId));
        map.put("weight",recycleService.getWeight(recycleId));
        if (!redisUtil.hasKey("sale")) {
            map.put("sale", Consts.SALE);
        } else {
            map.put("sale",redisUtil.get("sale"));
        }
        return map;
    }

    /**
     * 生成回收记录
     * @param weight
     * @param names
     */
    @ResponseBody
    @PostMapping("/addSaleRecord")
    public int addSaleRecord(float money,float weight,String names,Integer[] recordId){
        System.out.println(money);
        System.out.println(weight);
        System.out.println(Arrays.toString(recordId));
        try{
            StringBuilder id = new StringBuilder();
            double sale = 2.50;
            SaleRecord saleRecord = new SaleRecord();
            for (Integer i : recordId){
                id.append(i.toString());
                id.append(" ");
            }
            saleRecord.setSaleWeight(weight);
            saleRecord.setNames(names);
            saleRecord.setSell(sale);
            saleRecord.setSaleMoney(money);
            saleRecord.setRecordId(id.toString());
            System.out.println(saleRecord);
            saleRecordService.addSaleRecord(saleRecord,recordId);
            return 1;
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    @ResponseBody
    @GetMapping("/getSaleRecordList")
    public List<SaleRecord> getSaleRecordList(){
        return saleRecordService.getSaleRecordList();
    }


    @ResponseBody
    @PostMapping("/getAimRecordList")
    public List<Record> getAimRecordList(@RequestBody Map<String, Object> params){
        List<Record> records = new ArrayList<> ();
        String id = (String)params.get("id");
        if(id!=null){
            System.out.println(id);
            String[] recordId = id.split(" ");
            System.out.println(Arrays.toString(recordId));
            System.out.println(recordService.getAimRecordList(recordId));
            records = recordService.getAimRecordList(recordId);
        }
        return records;
    }

    private ByteArrayInputStream parse(OutputStream out) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos = (ByteArrayOutputStream) out;
        return new ByteArrayInputStream(baos.toByteArray());
    }
}
